package com.qingyan.boot.manage;

import com.mybatisflex.codegen.config.GlobalConfig;
import com.mybatisflex.codegen.config.PackageConfig;
import com.mybatisflex.codegen.config.ServiceConfig;
import com.mybatisflex.codegen.config.ServiceImplConfig;
import com.mybatisflex.codegen.constant.TemplateConst;
import com.mybatisflex.codegen.entity.Table;
import com.mybatisflex.codegen.generator.IGenerator;
import com.mybatisflex.core.util.StringUtil;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @author csp 2024-04-13
 */
public class BizImplGenerator implements IGenerator {

    private String templatePath;

    public BizImplGenerator() {
        this("/templates/enjoy/bizImpl.tpl");
    }

    public BizImplGenerator(String templatePath) {
        this.templatePath = templatePath;
    }

    @Override
    public void generate(Table table, GlobalConfig globalConfig) {

        if (!globalConfig.isServiceImplGenerateEnable()) {
            return;
        }

        PackageConfig packageConfig = globalConfig.getPackageConfig();
        ServiceConfig serviceImplConfig = (ServiceConfig) globalConfig.getCustomConfig().get("bizImplConfig");
        String sourceDir = StringUtil.isNotBlank(serviceImplConfig.getSourceDir()) ? serviceImplConfig.getSourceDir() : packageConfig.getSourceDir();

        String servicePackagePath = ((String) globalConfig.getCustomConfig().get("bizConfigImplPackage")).replace(".", "/");
        File serviceImplJavaFile = new File(sourceDir, serviceImplPackagePath + "/" + table.buildServiceImplClassName() + ".java");

        if (serviceImplJavaFile.exists() && !serviceImplConfig.isOverwriteEnable()) {
            return;
        }


        Map<String, Object> params = new HashMap<>(4);
        params.put("table", table);
        params.put("packageConfig", packageConfig);
        params.put("serviceImplConfig", serviceImplConfig);
        params.put("javadocConfig", globalConfig.getJavadocConfig());
        params.putAll(globalConfig.getCustomConfig());
        globalConfig.getTemplateConfig().getTemplate().generate(params, templatePath, serviceImplJavaFile);

        System.out.println("ServiceImpl ---> " + serviceImplJavaFile);
    }

    @Override
    public String getTemplatePath() {
        return templatePath;
    }

    @Override
    public void setTemplatePath(String templatePath) {
        this.templatePath = templatePath;
    }

}
